<script setup lang="tsx">
import { ref, onMounted, reactive, nextTick, watch } from 'vue'
import { deleteUser, getPageList, editUser } from '@/api/user/admin'
import { UserItem } from '@/api/user/types'
import { useRouter, useRoute } from 'vue-router'
import { ContentWrap } from '@/components/ContentWrap'
import { ElMessage, ElMessageBox } from 'element-plus'

const searchFormInit = {
  keywords: '',
  status: undefined,
  pageNum: 1,
  pageSize: 10
}

// 搜索表单数据
const searchForm = reactive({ ...searchFormInit })

// 数据状态
const pageList = ref<UserItem[]>([])
const loading = ref(false)
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 性别映射
const sexMap = {
  1: '男',
  2: '女',
  3: '未知'
}

const router = useRouter()
const route = useRoute()

// 获取用户列表
const fetchPageList = async () => {
  loading.value = true
  try {
    // 构造查询参数
    const params: UserQueryParams = {
      keywords: searchForm.keywords || '',
      status: searchForm.status,
      pageNum: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    }

    // 只添加非空/默认值的搜索条件
    // 注意：根据 UserQueryParams 类型调整字段
    // 移除不适用于用户查询的订单相关字段

    const response = await getPageList(params) // 修正API调用
    if (response.code === 200) {
      pageList.value = response.data.list
      pagination.value.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchPageList()
}

// 重置搜索条件
const handleReset = () => {
  Object.assign(searchForm, searchFormInit)
  pagination.value.currentPage = 1
  fetchPageList()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  fetchPageList()
}

const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val
  fetchPageList()
}

// 删除用户记录
const deleteRecord = async (row: UserItem) => {
  try {
    await deleteUser(row.userId) // 假设是删除用户，需要根据实际API调整
    ElMessage.success('删除成功')
    fetchPageList() // 重新获取列表
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 禁用/启用用户
const toggleUserStatus = async (row: UserItem) => {
  try {
    // 确认提示
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}用户"${row.name}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用编辑接口更新用户状态
    const newStatus = row.status === 1 ? 0 : 1
    await editUser({ ...row, status: newStatus })

    // 更新成功后刷新列表或直接更新状态
    row.status = newStatus
    ElMessage.success(`${newStatus === 1 ? '启用' : '禁用'}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${row.status === 1 ? '禁用' : '启用'}失败`)
    }
  }
}

const jumpToEditPage = (data: UserItem) => {
  router.push({ name: 'UserEdit', params: { id: data.userId } })
}

const jumpToAddPage = () => {
  router.push({ name: 'UserCreate' })
}

// 新增用户
const jumpUserCreate = () => {
  router.push({ name: 'UserCreate' })
}

// 查看订单详情
const jumpDetailPage = (user: UserItem) => {
  router.push({
    name: 'UserDetail',
    query: { userId: user.userId }
  })
}

// 监听路由变化，确保页面激活时刷新数据
watch(
  () => route.name,
  (newVal) => {
    if (newVal === 'UserPageList') {
      fetchPageList()
    }
  },
  { immediate: true }
)

// 监听路由查询参数变化，如果包含refresh=1则刷新数据
watch(
  () => route.query,
  (newVal) => {
    if (newVal.refresh === '1') {
      fetchPageList()
    }
  },
  { deep: true, immediate: true }
)

// 初始化
onMounted(() => {
  fetchPageList()
})
</script>

<template>
  <ContentWrap title="顾客列表" message="展示顾客主要信息等">
    <!-- 搜索表单 -->
    <div>
      <el-form :model="searchForm" label-width="100px" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keywords"
            placeholder="请输入名称，电话，网站，模糊查询"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用中" :value="1" />
            <el-option label="禁用中" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="jumpUserCreate">新增顾客</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表 -->
    <el-table :data="pageList" style="width: 100%" v-loading="loading" border>
      <el-table-column prop="userId" label="用户ID" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="branch" label="网点" />
      <el-table-column prop="sex" label="性别">
        <template #default="scope">
          {{ sexMap[scope.row.sex] || '未知' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用中' : '禁用中' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="updatedAt" label="更新时间" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <div class="button-container">
            <el-button size="small" type="info" @click="jumpDetailPage(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="jumpToEditPage(scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'danger' : 'primary'"
              @click="toggleUserStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteRecord(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; text-align: right"
    />
  </ContentWrap>
</template>

<style scoped>
.button-container {
  display: flex;
  flex-direction: column; /* 垂直排列，实现换行效果 */
  align-items: center; /* 右对齐 */
  gap: 8px; /* 按钮间距 */
}
.button-container :deep(.el-button) {
  margin: 0; /* 重置按钮默认外边距 */
}
</style>
